package com.iflysse.controller;

import com.iflysse.common.ResultEnum;
import com.iflysse.pojo.Users;
import com.iflysse.pojo.bo.req.QueryUserInfoBoReq;
import com.iflysse.pojo.bo.req.UserBoReq;
import com.iflysse.pojo.bo.resp.QueryUserInfoBoResp;
import com.iflysse.pojo.bo.resp.UserBoResp;
import com.iflysse.pojo.vo.common.CommonVoResp;
import com.iflysse.pojo.vo.req.*;
import com.iflysse.pojo.vo.resp.*;
import com.iflysse.services.UserService;
import com.iflysse.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/user")
@Api(value = "公用用户模块接口")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/checkEmailLinkIsOk")
    @ApiOperation(value = "校验链接是否有效")
    public CheckEmailLinkIsOkVoResp doCheckEmailLinkIsOk(CheckEmailLinkIsOkVoReq checkEmailLinkIsOkVoReq) {

        CheckEmailLinkIsOkVoResp checkEmailLinkIsOkVoResp = new CheckEmailLinkIsOkVoResp();
        if (checkEmailLinkIsOkVoReq != null) {
            // TODO : 校验链接是否有效
        }
        return checkEmailLinkIsOkVoResp;
    }


    @PostMapping("/updateUserHeadImage")
    @ApiOperation(value = "修改头像接口")
    public CommonVoResp doUpdateUserHeadImage(UserHeadImageVoReq userHeadImageVoReq) {
        CommonVoResp commonVoResp = new CommonVoResp();
        return commonVoResp;
    }


    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "修改用户信息接口")
    public CommonVoResp doUpdateUserInfo(UpdateUserInfoVoReq updateUserInfoVoReq) {
        CommonVoResp commonVoResp = new CommonVoResp();
        //进行判断修改信息内容不为空
        if (updateUserInfoVoReq != null) {
            if (StringUtils.isEmpty(updateUserInfoVoReq.getUserId())
                    || StringUtils.isEmpty(updateUserInfoVoReq.getNickName())
                    || StringUtils.isEmpty(updateUserInfoVoReq.getName())
                    || StringUtils.isEmpty(updateUserInfoVoReq.getGender())
                    || StringUtils.isEmpty(updateUserInfoVoReq.getPersonalSignature())
                    || StringUtils.isEmpty(updateUserInfoVoReq.getEmail())
                    || StringUtils.isEmpty(updateUserInfoVoReq.getHobby())) {
                commonVoResp.setCode(ResultEnum.NOPARAMETER.getCode());
                commonVoResp.setMsg(ResultEnum.NOPARAMETER.getMsg());
                return commonVoResp;
            }
        }

//        commonVoResp.setCode(3000);
//        commonVoResp.setMsg("用户信息修改成功。");
//        UserResp userResp = new UserResp();
//        userResp.setRole(reulst.getRole());
//        userResp.setToken(reulst.getToken());
//        userResp.setUserId(reulst.getUserId());
//        commonVoResp.setResult(userResp);
        return commonVoResp;
    }


    @PostMapping("/queryUserInfo")
    @ApiOperation(value = "查询用户信息，老师端学生端共有")
    public QueryUserInfoVoResp queryUserInfo(QueryUserInfoVoReq queryUserInfoVoReq) {

        QueryUserInfoVoResp queryUserInfoVoResp = new QueryUserInfoVoResp();

        QueryUserInfoResp result = new QueryUserInfoResp();
        queryUserInfoVoResp.setResult(result);

        QueryUserInfoBoReq queryUserInfoBoReq = new QueryUserInfoBoReq();
        queryUserInfoBoReq.setUserId(queryUserInfoVoReq.getUserId());
        queryUserInfoBoReq.setRole(queryUserInfoVoReq.getRole());

        QueryUserInfoBoResp queryUserInfoBoResp = new QueryUserInfoBoResp();
        if (queryUserInfoVoReq != null) {
            queryUserInfoBoResp = userService.selectByBothId(queryUserInfoBoReq);
        } else {
            queryUserInfoVoResp.setCode(404);
            queryUserInfoVoResp.setMsg("查询失败，输入的角色或学号错误。");
            return queryUserInfoVoResp;
        }
        result.setEmail(queryUserInfoBoResp.getEmail());
        result.setBaseImg(queryUserInfoBoResp.getBaseImg());
        result.setGender(queryUserInfoBoResp.getGender());
        result.setHobby(queryUserInfoBoResp.getHobby());
        result.setTeacherId(queryUserInfoBoResp.getTeacherId());
        result.setName(queryUserInfoBoResp.getName());
        result.setNickName(queryUserInfoBoResp.getNickName());
        result.setPersonalSignature(queryUserInfoBoResp.getPersonalSignature());

        queryUserInfoVoResp.setCode(200);
        queryUserInfoVoResp.setMsg("查询成功");

        return queryUserInfoVoResp;

    }


    @PostMapping("/resetPassword")
    @ApiOperation(value = "用户重置密码接口")
    public CommonVoResp resetPassword(ResetPasswordVoReq resetPasswordVoReq) {
        /**
         * TODO  1：校验新密码和确认新密码是否正确    2：校验验证码是否正确   3：完成重置密码
         */
        CommonVoResp commonVoResp = new CommonVoResp();

        if (resetPasswordVoReq != null) {
            List<Users> list = userService.selectById(resetPasswordVoReq.getUserId());
            if (list != null) {
                if (resetPasswordVoReq.getPassWord().equals(resetPasswordVoReq.getConfirmPassword())) {
                    userService.resetPassword(resetPasswordVoReq);
                    commonVoResp.setCode(200);
                    commonVoResp.setMsg("重置密码成功！");
                }
            } else {
                commonVoResp.setCode(404);
                commonVoResp.setMsg("用户不存在！");
            }

        }
        return commonVoResp;
    }


    @PostMapping("/retrievePassword")
    @ApiOperation(value = "用户找回密码接口")
    public CommonVoResp retrievePassword(RetrievePasswordVoReq retrievePasswordVoReq) {
        /**
         * TODO  1：校验姓名和邮箱是否一致    2：校验验证码是否正确   3：链接后追加参数：用户的唯一标识   4：邮件发送
         */
        CommonVoResp commonVoResp = new CommonVoResp();
        if (retrievePasswordVoReq != null) {
            //通过check student_name and email 地址来判断姓名和邮箱是否一致。
            List<Users> list = userService.checkstuname_email(retrievePasswordVoReq.getUserName(), retrievePasswordVoReq.getEmail());
            if (list != null) {
                commonVoResp.setCode(200);
                commonVoResp.setMsg("链接发送成功");
            } else {
                commonVoResp.setCode(404);
                commonVoResp.setMsg("姓名和邮箱不一致。");
            }
        }
        return commonVoResp;
    }


    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口")
    public UserVoResp login(HttpServletRequest request, UserVoReq userVoReq) throws UnsupportedEncodingException {

        UserVoResp userVoResp = new UserVoResp();
        /**
         * TODO 调用登录的业务接口，获取返回信息
         */

        //前端传参的非空检查
        if (userVoReq != null) {
            if (StringUtils.isEmpty(userVoReq.getCode())
                    || StringUtils.isEmpty(userVoReq.getCodeId())
                    || StringUtils.isEmpty(userVoReq.getPassWord())
                    || StringUtils.isEmpty(userVoReq.getUserName())) {
                userVoResp.setCode(ResultEnum.NOPARAMETER.getCode());
                userVoResp.setMsg(ResultEnum.NOPARAMETER.getMsg());
                return userVoResp;
            }
        }
        //验证码的检查
        String fromSessionCode = (String) request.getSession().getAttribute(userVoReq.getCodeId());

        //测试环境暂时不可使用，生产环境可用
//        if(!userVoReq.getCode().equals(fromSessionCode)){
//            userVoResp.setCode(ResultEnum.CODEERROR.getCode());
//            userVoResp.setMsg(ResultEnum.CODEERROR.getMsg());
//            return userVoResp;
//        }

        //账户和密码的校验
        UserBoReq userBoReq = new UserBoReq();
        userBoReq.setUserName(userVoReq.getUserName());
        userBoReq.setPassWord(userVoReq.getPassWord());

        UserBoResp reulst = userService.login(userBoReq);
        //token信息
        String token = JwtUtil.createToken(reulst.getUserId(), reulst.getRole());





        /*UserResp userResp = new UserResp();
        userResp.setRole("1");
        userResp.setUserId("123123");
        userResp.setToken("qweqweqwe");*/
        userVoResp.setCode(3000);
        userVoResp.setMsg("登录成功");
        UserResp userResp = new UserResp();
        userResp.setRole(reulst.getRole());
        userResp.setToken(reulst.getToken());
        userResp.setUserId(reulst.getUserId());
        userVoResp.setResult(userResp);
        return userVoResp;
    }


    @PostMapping("/code")
    @ApiOperation(value = "图形验证码")
    public CodeVoResp createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("验证码请求");
        //设置打印到浏览器的数据格式
        response.setContentType("image/gif");

        // 清除页面缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //创建一张缓存图片
        BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);

        //根据图片对象获取出图片的绘制对象
        Graphics g = image.getGraphics();
        //根据绘制对象来给图片增加背景颜色
        g.setColor(Color.red);
        //根据绘制对象来确定背景颜色的范围
        g.fillRect(0, 0, 100, 30);

        //随机生成一个数
        Random r = new Random();

        //往图片中绘制验证码  4
        g.setColor(Color.BLACK);

        StringBuffer sbCode = new StringBuffer();
        int x = 20;
        for (int i = 0; i < 4; i++) {
            int txt = r.nextInt(10);
            String str = String.valueOf(txt);
            g.drawString(str, x, 20);//
            sbCode.append(str);
            x = x + 20;
        }

        //TODO 生成验证码的唯一标识
        String codeId = "code";

        //TODO 设置session的有效期
        //将验证码存到session中，方便登录时来获取这个验证去校验用户登陆时所输入的验证码是否正确
        request.getSession().setAttribute(codeId, sbCode.toString());

        BASE64Encoder encoder = new BASE64Encoder();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "gif", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        //删除 \r\n
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");

        System.out.println(png_base64);


        CodeVoResp codeVoResp = new CodeVoResp();
        CodeResp codeResp = new CodeResp();
        codeResp.setCodeId(codeId);
        codeResp.setBaseImage(png_base64);
        codeVoResp.setResult(codeResp);
        codeVoResp.setCode(1000);
        codeVoResp.setMsg("验证码生成成功");
        return codeVoResp;


    }
}
